package com.xxx.client.registry;

import com.xxx.client.handler.RemoteCallClient;
import com.xxx.registry.ServerInfo;
import com.xxx.service.DemoService;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelFutureListener;
import org.apache.curator.framework.CuratorFramework;
import org.apache.curator.framework.recipes.cache.*;

import java.util.Map;

/**
 * Created by louisyuu on 2020/4/29 下午4:21
 */
public class ServerNodeChangeListener implements PathChildrenCacheListener {


    @Override
    public void childEvent(CuratorFramework curatorFramework, PathChildrenCacheEvent event) throws Exception {
//        System.out.println("=================Server node changed============" + event.getType());

        String serverAddress = event.getData().getPath().substring(event.getData().getPath().indexOf("/") + 1);
        Map<String, ChannelInfo> availableServers = RemoteCallClient.getInstance().getAvailableServers();
        switch (event.getType()) {
            case CHILD_REMOVED:

                if (!availableServers.isEmpty()) {

                    invalidServerNodeEvict(availableServers, serverAddress);

                    System.out.println("===============Disconnect from " + serverAddress + "=============");

                    System.out.println("===============[Server Offline] current available servers are " + availableServers);

                }
                break;
            case CHILD_ADDED:
                String[] split = serverAddress.split(":");
                ServerInfo serverInfo = new ServerInfo();
                serverInfo.setHost(split[0]);
                serverInfo.setPort(Integer.valueOf(split[1]));
                serverInfo.setServerAddress(serverAddress);
                serverInfo.setServerPath("/" + serverAddress);

                RemoteCallClient.getInstance().createProxy(DemoService.class,
                        "com.xxx.service.DemoService.demo", serverInfo);

                System.out.println("===============[Server Online] current available servers are " + availableServers);

                break;
        }
    }


    /**
     * 失效server node 驱逐
     */
    public static ChannelInfo invalidServerNodeEvict(Map<String, ChannelInfo> availableServers, String serverAddress) {

        ChannelInfo channelInfo = availableServers.remove(serverAddress);

        return channelInfo;


    }

}
